import { useEffect, useState } from 'react';
import { DatePicker } from 'antd';
import { useRouter } from 'next/router';
import moment from 'moment';
import Cookies from 'js-cookie';
import { connect } from 'react-redux';
import { setSelectDate, setSelectDateRange, setProductInfo } from '@/store/actions/order';
import { getOneWeekDate } from '@/utils';
// css
import styles from '@/styles/CommonOrder.module.scss';

const { RangePicker } = DatePicker;
const dateFormat = 'YYYY-MM-DD',
    weekFormat = 'dddd';

const MyDatePicker = ({ _setSelectDate, _setSelectDateRange, _setProductInfo, data: { target, goodsId, goodsExtendName, buyLimit }, order: { date } }) => {

    const isHotel = target === '/hotel';
    const { predefinedDay } = buyLimit || {};
    
    const router = useRouter();
    const dates = getOneWeekDate();

    // 初始化 date
    const { start_date, end_date } = router.query;
    const today = start_date ? moment(start_date) : moment().add(0, 'days'),
        tomorrow = end_date ? moment(end_date) : moment().add(1, 'days');

    // picker
    const [defaultDate, setDefaultDate] = useState(new Date());
    const [currDate, setCurrDate] = useState(start_date ? { date: start_date } : dates[0]);
    const [dateList, setDateList] = useState(dates);

    const [rangeDate, setRangeDate] = useState([today, tomorrow]);
    const [rangeDates, setRangeDates] = useState([]);

    const [priceList, setPriceList] = useState([]);

    // init
    useEffect(() => {

        Cookies.set('order_select_date', start_date || dates[0].date);
        Cookies.set('order_hotel_startDate', start_date);
        Cookies.set('order_hotel_endDate', end_date);

        let timer = null,
            req_time = 1;
        timer = setInterval(() => {
            const prices = JSON.parse(sessionStorage.getItem('price_calendar'));
            if (req_time >= 5) {
                clearInterval(timer)
            }
            setPriceList(prices);
            req_time ++;
        }, 1000);
        
        // 酒店获取价格
        if(isHotel){
            _setProductInfo({
                goodsId,
                goodsExtendName,
                startDate: moment(today).format(dateFormat),
                endDate: moment(tomorrow).format(dateFormat),
                amount: Cookies.get('order_number') || 1,
            })
        }

        // 非酒店
        if(!isHotel){
            _setSelectDate(start_date);
        }        

        return function () {
            clearInterval(timer);
        }
    }, []);

    // 监听日期更改
    useEffect(() => {
        if (date) {
            dates.map(item => {
                item.checked = false;
                if (date == item.date) {
                    item.checked = true;
                }
                return item
            })
            setDateList([...dates]);
            setCurrDate({ date });
        }
    }, [date]);

    // 更改日期（自定义前七天）
    function selectDate(idx) {
        const start_date = Cookies.get('extra_start_date');
        if (dates[idx].date < start_date || (predefinedDay > 0 && idx >= predefinedDay)) {
            return false;
        }
        for (let i = 0; i < dates.length; i++) {
            const item = dates[i];
            if (i === idx) {
                item.checked = true;
                setCurrDate(item);
                _setSelectDate(item.date);
                Cookies.set('order_select_date', item.date);
            } else {
                item.checked = false;
            }
        }
        setDateList([...dates]);
    }
    // 禁用开始时间(开始时间不能大于当前时间)
    function disabledDate(current) {
        let start_date = Cookies.get('extra_start_date');
        let yesterday = moment().add(-1, 'days'),
            f_yesterday = moment(yesterday).format(dateFormat);
      
        if (start_date && f_yesterday < start_date) {
            yesterday = new Date(start_date);
        }
        if (current <= yesterday) {
            return true
        }
        if(predefinedDay > 7){
            let dfDate = new Date(moment(defaultDate).format(dateFormat)),
                allDay = dfDate.getDate() + predefinedDay,
                toDate = new Date(dfDate.setDate(allDay));
            if(current > toDate){
                return true
            }
        }
        if (current > defaultDate) {
            return false
        }
        return true
    }
    function disabledRangeDate(current) {
        let start_date = Cookies.get('extra_start_date');
        let yesterday = moment().add(-1, 'days'),
            f_yesterday = moment(yesterday).format(dateFormat);
        if (start_date && f_yesterday < start_date) {
            yesterday = new Date(start_date);
        }
        if (current <= yesterday) {
            return true
        }
        if(predefinedDay > 0){
            let dfDate = new Date(moment(defaultDate).format(dateFormat)),
                allDay = dfDate.getDate() + predefinedDay,
                toDate = new Date(dfDate.setDate(allDay));
            if(current > toDate){
                return true
            }
        }
        if (!rangeDates || rangeDates.length === 0 || (rangeDates[0] && current > rangeDates[0])) {
            return false
        }
        return true
    }
    // 根据价格日历，渲染日期
    function renderSelfDate(current) {
        const curr_date = moment(current).format('YYYY/MM/DD');
        let text = "", price = "";
        for (let i = 0, len = priceList.length; i < len; i++) {
            const item = priceList[i],
                  stock = item.stock;
            if (item.priceDate === curr_date) {
                if (stock == -1) {
                    text = "库存充足";
                }else {
                    text = `库存${stock >= 1000 ? '999' : stock}`;
                } 
                price = "￥" + item.salePrice;
                break
            }
        }
        return (
            <div className="ant-picker-cell-inner">
                {current.date()}
                <p dangerouslySetInnerHTML={{ __html: text || '&nbsp;' }}></p>
                <p dangerouslySetInnerHTML={{ __html: price || '&nbsp;' }}></p>
            </div>
        );
    }
    // 选择日期
    function onDateChange(value) {
        const date = moment(value).format(dateFormat);
        setCurrDate({ date });
        _setSelectDate(date);
        Cookies.set('order_select_date', date);
    }
    function onDateRangeChange(value) {
        const [startDate, endDate] = [
            moment(value[0]).format(dateFormat),
            moment(value[1]).format(dateFormat)
        ];
        setRangeDates(value);
        setRangeDate(value);
        _setSelectDateRange({startDate, endDate});
        _setProductInfo({
            goodsId,
            goodsExtendName,
            startDate,
            endDate,
            amount: Cookies.get('order_number') || 1,
        });
        Cookies.set('order_hotel_startDate', startDate);
        Cookies.set('order_hotel_endDate', endDate);
    }
    // 打开rangepicker，重置日期
    function onOpenChange(open) {
        if (open) {
            setRangeDates([])
        }
    }

    return (
        <>
            <div className={styles['product-calendar']}>
                {
                    isHotel
                    ? <div className={styles['hotel-calendar']}>
                        <span className={styles['date']}>{moment(rangeDate[0]).format(dateFormat)}</span>
                        <span> 入住（{moment(rangeDate[0]).format(weekFormat)}）</span>
                        <em>-</em>
                        <span className={styles['date']}>{moment(rangeDate[1]).format(dateFormat)}</span>
                        <span> 退房（{moment(rangeDate[1]).format(weekFormat)}）</span>
                        <div className={styles['more-date']}>
                            <span>更多日期</span>
                            <RangePicker
                                format={dateFormat}
                                defaultValue={[today, tomorrow]}
                                disabledDate={disabledRangeDate}
                                dateRender={current => renderSelfDate(current)}
                                onCalendarChange={val => setRangeDates(val)}
                                onChange={val => { onDateRangeChange(val) }}
                                onOpenChange={onOpenChange}
                            />
                        </div>
                      </div>
                    : <>
                        <ul>
                            {
                                dateList.map((item, index) => {
                                    const start_date = Cookies.get('extra_start_date');
                                    const { date, checked } = item;
                                    return (
                                        <li className={[
                                            checked && styles['selected'], 
                                            (date < start_date) && styles['disabled'], 
                                            (predefinedDay > 0 && index >= predefinedDay) && styles['disabled']
                                        ].join(' ')} 
                                            onClick={() => selectDate(index)}
                                            key={index}
                                        >
                                            <p>{item.date}</p>
                                            <span>{item.week}</span>
                                        </li>
                                    )
                                })
                            }
                            <li className={[styles['more-date'], !(predefinedDay < 0 || predefinedDay > 7) && styles['disabled']].join(' ')}>
                                <span>更多日期</span>
                                {
                                    (predefinedDay < 0 || predefinedDay > 7)
                                    ? <DatePicker
                                        showToday={false}
                                        disabledDate={disabledDate}
                                        onChange={val => onDateChange(val)}
                                        dateRender={current => renderSelfDate(current)}
                                    />
                                    : ""
                                }
                            </li>
                        </ul>
                        <p><span>已选日期：</span>{currDate.date}</p>
                      </>
                }
            </div>
        </>
    )
}
const mapStateToProps = (state) => {
    return {
        order: state.order
    }
}
const mapDispatchToProps = (dispatch) => {
    return {
        _setSelectDate: (v) => dispatch(setSelectDate(v)),
        _setSelectDateRange: (v) => dispatch(setSelectDateRange(v)),
        _setProductInfo: (v) => dispatch(setProductInfo(v))
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(MyDatePicker)